import Icon, {
  AreaChartOutlined,
  BarChartOutlined,
  DotChartOutlined,
  FundOutlined,
  HeatMapOutlined,
  LineChartOutlined,
  PieChartOutlined,
  RadarChartOutlined,
  SlidersOutlined,
} from "@ant-design/icons";
import { lazy } from "react";
import { Redirect } from "react-router-dom";
import { IRouteItem } from "src/constants/interfaces/IRouterItem";
import NotFound from "./exceptions/notFound";
import Snapshot from "./system/snapshot";
import { ReactSVG } from "react-svg";
import ContentSkeleton from "src/components/contentSkeleton";
import IFrame from "./system/iframe";

/**
 * 异步加载工具
 * 带有webpack打包名
 */
const loader = (path: string) =>
  lazy(() => import(/* webpackChunkName: '[request]-[index]' */ `./${path}`));

const config = (window as any).__config;

function parseRoute(route: any) {
  let item = { ...route };
  if (route.icon) {
    item.icon = <Icon component={() => <ReactSVG src={route.icon} />} />;
  }
  if (route.routes) {
    let routes = [];
    for (const child of route.routes) {
      routes.push(parseRoute(child));
    }
    item.routes = routes;
  } else if (route.component) {
    item.component = loader(route.component);
  } else if (route.url) {
    item.children = <IFrame src={route.url} />;
  } else if (route.picture) {
    item.children = <Snapshot src={route.picture} />;
  } else if (route.to) {
    item.children = <Redirect to={route.to} />;
  } else {
    item.component = ContentSkeleton;
  }

  return item;
}

const icons = [
  <AreaChartOutlined />,
  <PieChartOutlined />,
  <BarChartOutlined />,
  <DotChartOutlined />,
  <LineChartOutlined />,
  <RadarChartOutlined />,
  <HeatMapOutlined />,
  <FundOutlined />,
  <SlidersOutlined />,
];

export function parseRoutes(menuList: any[]) {
  let routes = [];
  for (const child of menuList) {
    const route = parseRoute(child);
    // 没有图标，随机指定一个
    if (!route.icon) {
      route.icon = icons[Math.floor(Math.random() * icons.length)];
    }
    routes.push(route);
  }
  routes.push(
    {
      hide: true,
      name: "测试页面",
      path: "/test",
      component: loader("system/test"),
      requireAuth: false,
    },
    {
      hide: true,
      path: "/**",
      component: NotFound,
      name: "404页面未找到",
    },
  );
  return routes;
}

export const routeItems: IRouteItem[] = parseRoutes(config.routes);